from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin
from untils.myjwt import verify_jwt
from blog.models import User
from django.contrib.auth.models import AnonymousUser
class Middleware(MiddlewareMixin):
    def process_request(self, request):
        public_paths = ('/picture/', '/login/', '/register/', '/code/', '/public/articles/')
        if request.path.startswith(public_paths):
            return
        auth_header = request.META.get('HTTP_AUTHORIZATION', '').strip()
        if not auth_header.startswith('Bearer '):
            return JsonResponse({'message': '请先登录或提供有效的token'}, status=401)
        try:
            _, token = auth_header.split(' ', 1)
            payload, status = verify_jwt(token)
            if status != 0:
                return JsonResponse({'message':'Token验证失败了喵'}, status=401)
            request.user_id = payload.get('user_id')
            if not request.user_id:
                return JsonResponse({'message':'token缺失id'}, status=401)
            try:
                request.user = User.objects.get(id=request.user_id)
            except User.DoesNotExist:
                return JsonResponse({'message': '用户不存在'}, status=401)
        except (ValueError, User.DoesNotExist):
            return JsonResponse({'message': '无效的Token'}, status=401)